#include "common/pch.h"

#include <format>

#include <cftf/loger/syslog.h>

#include "map/gridmap.h"
#include "map/map.h"
#include "map/gridstates.h"
#include "system/grid/grid.h"
#include "system/grid/ngrid.h"

GridState::~GridState()
{
    cftf::loger::SysLog::Instance().Deubg("GridState destroyed");
}

void InvalidState::Update(Map&, NGridType&, game::system::grid::GridInfo&, const unsigned int& /*x*/, const unsigned int& /*y*/, const unsigned int&) const
{
}

void ActiveState::Update(Map& m, NGridType& grid, game::system::grid::GridInfo& info, const unsigned int& x, const unsigned int& y, const unsigned int& t_diff) const
{
    // Only check grid activity every (grid_expiry/10) ms, because it's really useless to do it every cycle
    info.UpdateTimeTracker(t_diff);
    if (info.getTimeTracker().Passed())
    {
        if (grid.ActiveObjectsInGrid() == 0 && !m.ActiveObjectsNearGrid(x, y))
        {
#if 0
            ObjectGridStoper stoper(grid);
            stoper.StopN();
#endif
            grid.SetGridState(game::system::grid::GRID_STATE_IDLE);
        }
        else
        {
            m.ResetGridExpiry(grid, 0.1f);
        }
    }
}

void IdleState::Update(Map& m, NGridType& grid, game::system::grid::GridInfo&, const unsigned int& x, const unsigned int& y, const unsigned int&) const
{
    m.ResetGridExpiry(grid);
    grid.SetGridState(game::system::grid::GRID_STATE_REMOVAL);
    cftf::loger::SysLog::Instance().Deubg(std::format("Grid[{},{}] on map {} moved to IDLE state", x, y, m.GetId()));
}

void RemovalState::Update(Map& m, NGridType& grid, game::system::grid::GridInfo& info, const unsigned int& x, const unsigned int& y, const unsigned int& t_diff) const
{
    if (!info.getUnloadLock())
    {
        info.UpdateTimeTracker(t_diff);
        if (info.getTimeTracker().Passed())
        {
            if (!m.UnloadGrid(x, y, false))
            {
                cftf::loger::SysLog::Instance().Warning(std::format("Grid[{},{}] for map {} differed unloading due to players or active objects nearby", x, y, m.GetId()));
                m.ResetGridExpiry(grid);
            }
        }
    }
}